﻿using Microsoft.Extensions.DependencyInjection;

namespace Service.Framework.ApplicationEventBus
{
    public class ApplicationEventBus : IApplicationEventBus
    {
        public ApplicationEventBus()
        {
        }


        public void Publish<TEventArgs>(TEventArgs eventArgs) where TEventArgs : IApplicationEventArgs
        {
            using (var scope = App.ServiceProvider.CreateScope())
            {
                var applicationEventHandler = scope.ServiceProvider.GetService<IApplicationEventHandler<TEventArgs>>();
                applicationEventHandler.Handle(eventArgs).GetAwaiter();
            }
        }




        public async Task PublishAsync<TEventArgs>(TEventArgs eventArgs) where TEventArgs : IApplicationEventArgs
        {
            await using (var scope = App.ServiceProvider.CreateAsyncScope())
            {
                var applicationEventHandler = scope.ServiceProvider.GetService<IApplicationEventHandler<TEventArgs>>();
                applicationEventHandler.Handle(eventArgs);
            }
        }
    }
}
